package com.harmonk.firstscene.ui.component

import android.Manifest
import android.R
import android.app.Application
import android.content.Context
import android.content.pm.PackageManager
import android.location.LocationManager
import android.os.Build
import android.util.Log
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.annotation.RequiresApi
import androidx.annotation.RequiresPermission
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.background
import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ExperimentalLayoutApi
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.imePadding
import androidx.compose.foundation.layout.navigationBarsPadding
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.staggeredgrid.LazyHorizontalStaggeredGrid
import androidx.compose.foundation.lazy.staggeredgrid.StaggeredGridCells
import androidx.compose.foundation.lazy.staggeredgrid.items
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.Card
import androidx.compose.material3.Checkbox
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.DatePicker
import androidx.compose.material3.DatePickerDialog
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ModalBottomSheet
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TimePicker
import androidx.compose.material3.rememberDatePickerState
import androidx.compose.material3.rememberModalBottomSheetState
import androidx.compose.material3.rememberTimePickerState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavController
import com.harmonk.firstscene.constants.Utils
import com.harmonk.firstscene.db.entity.EventNote
import com.harmonk.firstscene.ui.model.EventNoteViewModel
import com.harmonk.firstscene.ui.model.EventNoteViewModelFactory
import com.harmonk.firstscene.ui.model.QuickNoteViewModel
import com.harmonk.firstscene.ui.model.QuickNoteViewModelFactory
import kotlinx.coroutines.launch
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Date
import java.util.Locale

/**
 * 第三个Tab：显示这个TrafficEvent所属的TrafficNote
 */
@RequiresApi(Build.VERSION_CODES.R)
@OptIn(
    ExperimentalMaterial3Api::class, ExperimentalFoundationApi::class,
    ExperimentalLayoutApi::class
)
@Composable
fun EventNoteTab(
    modifier: Modifier = Modifier,
    navController: NavController,
    eventId: Long,
) {
    val noteViewModel: EventNoteViewModel = viewModel(
        factory = EventNoteViewModelFactory(LocalContext.current.applicationContext as Application)
    )
    val quickNoteViewModel: QuickNoteViewModel = viewModel(
        factory = QuickNoteViewModelFactory(LocalContext.current.applicationContext as Application)
    )
    val eventNotes by noteViewModel.eventNotes.observeAsState(emptyList())
    val quickNotes by quickNoteViewModel.quickNotes.observeAsState(emptyList())
    val sheetState = rememberModalBottomSheetState()
    var showSheetState by remember { mutableStateOf(false) }
    var noteState by remember { mutableStateOf(EventNote()) }
    val context = LocalContext.current
    // 权限请求启动器
    val locationPermissionLauncher = rememberLauncherForActivityResult(
        contract = ActivityResultContracts.RequestMultiplePermissions()
    ) { permissions ->
        // 处理权限结果
        val fineLocationGranted = permissions[Manifest.permission.ACCESS_FINE_LOCATION] ?: false
        val coarseLocationGranted = permissions[Manifest.permission.ACCESS_COARSE_LOCATION] ?: false

        if (fineLocationGranted || coarseLocationGranted) {
            // 输出获取位置权限成功的日志
            Log.i("EventNoteTab: ", "获取位置权限")
        }
    }
    var showLocationLoading by remember { mutableStateOf(false) }
    var showDeleteDialog by remember { mutableStateOf(false) }
    val coroutineScope = rememberCoroutineScope()


    // 检查并请求位置权限
    fun requestLocationPermission() {
        when {
            ContextCompat.checkSelfPermission(
                context,
                Manifest.permission.ACCESS_FINE_LOCATION
            ) == PackageManager.PERMISSION_GRANTED -> {
                // 已有权限，直接获取位置
                Log.i("EventNoteTab: ", "已获取位置权限")
            }

            else -> {
                // 请求权限
                locationPermissionLauncher.launch(
                    arrayOf(
                        Manifest.permission.ACCESS_FINE_LOCATION,
                        Manifest.permission.ACCESS_COARSE_LOCATION
                    )
                )
            }
        }
    }

    LaunchedEffect(Unit) {
        noteViewModel.loadTrafficNotesByEventId(eventId)
        quickNoteViewModel.loadAllQuickNotes()
        requestLocationPermission()
    }

    Column(
        modifier = modifier
            .fillMaxSize()
            .padding(16.dp)
    ) {
        Column(
            modifier = modifier
                .fillMaxWidth()
                .weight(1f)
                .verticalScroll(rememberScrollState())
        ) {
            eventNotes.forEach { note ->
                Card(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(bottom = 8.dp)
                        .combinedClickable(
                            onClick = {
                                noteState = note
                                showSheetState = true
                            },
                            onLongClick = {
                                noteState = note
                                // 弹出删除对话框
                                showDeleteDialog = true
                            }
                        )
                ) {
                    Column(
                        modifier = modifier
                            .fillMaxWidth()
                            .padding(12.dp),
                        Arrangement.spacedBy(8.dp)
                    ) {
                        Row(
                            modifier = Modifier.fillMaxWidth(),
                            horizontalArrangement = Arrangement.SpaceBetween
                        ) {
                            Text(
                                text = Utils.TimeFormatter.autoFormat(note.timestamp),
                                style = MaterialTheme.typography.bodySmall
                            )
                            if (note.recordLatLong) {
                                Text(
                                    text = Utils.CoordinateFormatter.formatLatitude(note.latitude) + " " + Utils.CoordinateFormatter.formatLongitude(
                                        note.longitude
                                    ),
                                    style = MaterialTheme.typography.bodySmall
                                )
                            }
                        }
                        HorizontalDivider(thickness = 1.dp)
                        Text(
                            text = note.content,
                            style = MaterialTheme.typography.bodyMedium
                        )
                    }
                }
            }
        }
        // 底部按钮
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(top = 16.dp),
            horizontalArrangement = Arrangement.SpaceEvenly
        ) {
            OutlinedButton(
                onClick = {
                    noteState = noteState.copy(
                        eventNoteId = 0L,
                        eventId = eventId,
                        timestamp = System.currentTimeMillis(),
                        content = "",
                        recordLatLong = false
                    )
                    showSheetState = true
                },
                modifier = Modifier.weight(1f),
                enabled = !showLocationLoading
            ) {
                Text("添加记事")
            }
        }
    }

    if (showDeleteDialog) {
        AlertDialog(
            onDismissRequest = { showDeleteDialog = false },
            title = { Text("确认删除") },
            text = { Text("确定要删除这条记事吗？此操作不可撤销。") },
            confirmButton = {
                Button(
                    onClick = {
                        coroutineScope.launch {
                            noteViewModel.deleteTrafficNote(noteState)
                        }
                        showDeleteDialog = false
                    }
                ) {
                    Text("确认")
                }
            },
            dismissButton = {
                TextButton(
                    onClick = { showDeleteDialog = false }
                ) {
                    Text("取消")
                }
            }
        )
    }

    if (showSheetState) {
        ModalBottomSheet(
            onDismissRequest = { showSheetState = false },
            sheetState = sheetState,
        ) {
            var showDatePicker by remember { mutableStateOf(false) }
            var showTimePicker by remember { mutableStateOf(false) }
            val datePickerState = rememberDatePickerState(
                initialSelectedDateMillis = noteState.timestamp
            )
            val timePickerState = rememberTimePickerState(
                initialHour = SimpleDateFormat(
                    "HH",
                    Locale.getDefault()
                ).format(Date(noteState.timestamp)).toInt(),
                initialMinute = SimpleDateFormat("mm", Locale.getDefault()).format(
                    Date(noteState.timestamp)
                ).toInt(),
                is24Hour = true
            )
            // 记事输入表单内容
            Column(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(16.dp)
                    .navigationBarsPadding()
                    .imePadding() // 处理输入法填充
            ) {
                Text("添加记事")
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.SpaceBetween
                ) {
                    OutlinedButton(
                        onClick = { showDatePicker = true },
                        modifier = Modifier.weight(1f)
                    ) {
                        Text(
                            SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(
                                Date(noteState.timestamp)
                            )
                        )
                    }

                    Spacer(modifier = Modifier.weight(0.1f))

                    OutlinedButton(
                        onClick = { showTimePicker = true },
                        modifier = Modifier.weight(1f)
                    ) {
                        Text(
                            SimpleDateFormat("HH:mm", Locale.getDefault()).format(
                                Date(noteState.timestamp)
                            )
                        )
                    }
                }

                OutlinedTextField(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(bottom = 12.dp),
                    value = noteState.content,
                    onValueChange = {
                        noteState = noteState.copy(content = it)
                    },
                    label = { Text("记事内容") }
                )

                if (quickNotes.isEmpty()) {
                    TextButton(
                        onClick = {
                        navController.navigate("quick_note")
                    }) {
                        Text("+ 添加快捷记事", style = MaterialTheme.typography.bodySmall)
                    }
                } else {
                    Row(
                        modifier = Modifier
                            .fillMaxWidth()
                    ) {
                        LazyHorizontalStaggeredGrid(
                            rows = StaggeredGridCells.Fixed(2),
                            horizontalItemSpacing = 4.dp,
                            verticalArrangement = Arrangement.spacedBy(4.dp),
                            modifier = Modifier
                                .fillMaxWidth()
                                .height(80.dp)
                        ) {
                            items(quickNotes) { quickNote ->
                                TextButton(
                                    contentPadding = PaddingValues(0.dp),
                                    onClick = {
                                        noteState = noteState.copy(content = quickNote.note)
                                    },
                                ) {
                                    Text(
                                        modifier = Modifier
                                            .background(
                                                MaterialTheme.colorScheme.surfaceVariant,
                                            )
                                            .padding(6.dp),
                                        text = quickNote.note,
                                        style = MaterialTheme.typography.bodySmall,
                                    )
                                }
                            }
                        }
                    }
                }
                // 添加是否记录经纬度开关
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.Center,
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    if (showLocationLoading) {
                        CircularProgressIndicator(
                            modifier = Modifier.size(24.dp),
                        )
                    }
                    Text("记录经纬度")
                    Checkbox(
                        checked = noteState.recordLatLong,
                        onCheckedChange = {
                            noteState = noteState.copy(recordLatLong = it)
                        }
                    )
                }

                // 其他选项和按钮
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.SpaceBetween
                ) {
                    OutlinedButton(onClick = { showSheetState = false }) {
                        Text("取消")
                    }
                    OutlinedButton(
                        onClick = {
                            // 保存记事
                            if (noteState.eventNoteId == 0L) {
                                if (noteState.recordLatLong) {
                                    showLocationLoading = true
                                    getCurrentLocationWithFallback(
                                        context = context,
                                        noteState = noteState,
                                        onLocationReceived = { updatedNote ->
                                            noteState = updatedNote
                                            Log.i("EventNoteTab: ", "获取位置成功${noteState}")
                                            noteViewModel.insertTrafficNote(noteState)
                                            showLocationLoading = false
                                            showSheetState = false
                                        }
                                    )
                                } else {
                                    noteViewModel.insertTrafficNote(noteState)
                                    showSheetState = false
                                }
                            } else {
                                noteViewModel.updateTrafficNote(noteState)
                                showSheetState = false
                            }
                        },
                        enabled = !showLocationLoading
                    ) {
                        Text("保存")
                    }
                }
            }
            if (showDatePicker) {
                DatePickerDialog(
                    onDismissRequest = { showDatePicker = false },
                    confirmButton = {
                        TextButton(
                            onClick = {
                                val selectedDate = datePickerState.selectedDateMillis
                                if (selectedDate != null) {
                                    // 更新事件时间（只更新日期部分）
                                    val calendar = Calendar.getInstance().apply {
                                        timeInMillis = noteState.timestamp
                                        val hour = get(Calendar.HOUR_OF_DAY)
                                        val minute = get(Calendar.MINUTE)

                                        timeInMillis = selectedDate
                                        set(Calendar.HOUR_OF_DAY, hour)
                                        set(Calendar.MINUTE, minute)
                                        set(Calendar.SECOND, 0)
                                        set(Calendar.MILLISECOND, 0)
                                    }
                                    noteState = noteState.copy(timestamp = calendar.timeInMillis)
                                }
                                showDatePicker = false
                            }
                        ) {
                            Text("确认")
                        }
                    },
                    dismissButton = {
                        TextButton(onClick = { showDatePicker = false }) {
                            Text("取消")
                        }
                    }
                ) {
                    DatePicker(state = datePickerState)
                }
            }
            if (showTimePicker) {
                AlertDialog(
                    onDismissRequest = { showTimePicker = false },
                    title = { Text("选择时间") },
                    text = {
                        TimePicker(state = timePickerState)
                    },
                    confirmButton = {
                        TextButton(
                            onClick = {
                                // 更新事件时间（只更新时间部分）
                                val calendar = Calendar.getInstance().apply {
                                    timeInMillis = noteState.timestamp
                                    set(Calendar.HOUR_OF_DAY, timePickerState.hour)
                                    set(Calendar.MINUTE, timePickerState.minute)
                                    set(Calendar.SECOND, 0)
                                    set(Calendar.MILLISECOND, 0)
                                }
                                noteState = noteState.copy(timestamp = calendar.timeInMillis)
                                showTimePicker = false
                            }
                        ) {
                            Text("确认")
                        }
                    },
                    dismissButton = {
                        TextButton(onClick = { showTimePicker = false }) {
                            Text("取消")
                        }
                    }
                )
            }
        }
    }
}

@RequiresApi(Build.VERSION_CODES.R)
private fun getCurrentLocationWithFallback(
    context: Context,
    noteState: EventNote,
    onLocationReceived: (EventNote) -> Unit,
    onError: () -> Unit = {}
) {
    val locationManager = context.getSystemService(Context.LOCATION_SERVICE) as LocationManager

    if (ActivityCompat.checkSelfPermission(
            context,
            Manifest.permission.ACCESS_FINE_LOCATION
        ) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(
            context,
            Manifest.permission.ACCESS_COARSE_LOCATION
        ) != PackageManager.PERMISSION_GRANTED
    ) {
        onError()
        return
    }

    try {
        val providers = listOf(
            LocationManager.GPS_PROVIDER,
            LocationManager.NETWORK_PROVIDER,
            LocationManager.PASSIVE_PROVIDER
        )

        // 使用递归方式尝试每个 provider
        tryNextProvider(
            locationManager,
            context,
            providers,
            0,
            noteState,
            onLocationReceived,
            onError
        )

    } catch (e: Exception) {
        Log.e("EventNoteTab", "获取位置失败", e)
        onError()
    }
}

@RequiresPermission(allOf = [Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION])
@RequiresApi(Build.VERSION_CODES.R)
private fun tryNextProvider(
    locationManager: LocationManager,
    context: Context,
    providers: List<String>,
    index: Int,
    currentNoteState: EventNote,
    onLocationReceived: (EventNote) -> Unit,
    onError: () -> Unit
) {
    // 如果已经尝试完所有 provider
    if (index >= providers.size) {
        onError()
        return
    }

    val provider = providers[index]

    if (locationManager.isProviderEnabled(provider)) {
        Log.i("EventNoteTab: ", "尝试 Provider: $provider")
        locationManager.getCurrentLocation(provider, null, context.mainExecutor) { location ->
            if (location != null) {
                Log.i("EventNoteTab: ", "从 $provider 获取位置成功: $location")
                val updatedNote = currentNoteState.copy(
                    latitude = location.latitude,
                    longitude = location.longitude,
                    recordLatLong = true
                )
                // 返回更新后的记事
                Log.i("EventNoteTab: ", "执行回调，更新后的记事: $updatedNote")
                onLocationReceived(updatedNote)
            } else {
                // 如果当前 provider 没有返回位置，尝试下一个
                tryNextProvider(
                    locationManager,
                    context,
                    providers,
                    index + 1,
                    currentNoteState,
                    onLocationReceived,
                    onError
                )
            }
        }
    } else {
        // 如果当前 provider 不可用，尝试下一个
        tryNextProvider(
            locationManager,
            context,
            providers,
            index + 1,
            currentNoteState,
            onLocationReceived,
            onError
        )
    }
}
